package com.net.shop.car.manager.ui.chezhoubian;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.net.shop.car.manager.R;
import com.net.shop.car.manager.api.model.Seller;
import com.net.shop.car.manager.api.model.SellerInfo;
import com.net.shop.car.manager.api.volley.VolleyCenter;
import com.net.shop.car.manager.api.volley.VolleyListenerImpl;
import com.net.shop.car.manager.api.volley.request.GetSellerInfo;
import com.net.shop.car.manager.api.volley.request.GetSellerList;
import com.net.shop.car.manager.api.volley.request.GetSellersTWO;
import com.net.shop.car.manager.api.volley.request.GetWaySaveInfo;
import com.net.shop.car.manager.api.volley.response.GetWaySaveResponse;
import com.net.shop.car.manager.api.volley.response.SellerInfoResponse;
import com.net.shop.car.manager.api.volley.response.SellerListResponse;
import com.net.shop.car.manager.api.volley.response.SellerTWOResponse;
import com.net.shop.car.manager.ui.CityChooseDialog;
import com.net.shop.car.manager.ui.FullScreenDialog;
import com.net.shop.car.manager.ui.viewholder.LujiuViewHolder;
import com.net.shop.car.manager.ui.viewholder.SellerInfoViewHolder;
import com.net.shop.car.manager.ui.viewholder.TravelViewHolder;
import com.net.shop.car.manager.ui.viewholder.TuoCheViewHolder;
import com.net.shop.car.manager.ui.viewholder.ViewHolder;
import com.net.shop.car.manager.utils.Constants.ServiceType;
import com.net.shop.car.manager.utils.StringUtils;

/**
 * 
 * 商家列表，主要包括保养，洗车，维修等
 * 
 * @author Deve
 * 
 */
public class SellerDialog extends FullScreenDialog implements
		OnItemClickListener {

	/**
	 * 
	 */
	private List<Seller> sellers = new ArrayList<Seller>();

	private FrameLayout container;

	private Map<Seller, SellerInfo> sellerInfos = new HashMap<Seller, SellerInfo>();

	/**
	 * 
	 */
	private boolean isDetailShow;

	/**
	 * 
	 */
	private int totalPages = 0;

	private int pageIndex = 1;

	/**
	 * 
	 */
	private View detailView;

	private CarCMPAdapter carCMPAdapter;

	private final ServiceType type;

	private TextView titleView;

	private String title;

	private ListView sellerListView;

	private TextView rightTextView;

	/**
	 * @param context
	 */
	public SellerDialog(Context context, ServiceType type) {
		super(context, R.style.Dialog_Fullscreen);
		this.type = type;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_seller);

		pageIndex = 1;
		initViews();
	}

	/**
	 * 
	 */
	private void initViews() {
		View view = findViewById(R.id.seller_title);

		view.findViewById(R.id.title_back_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});
		rightTextView = (TextView) view.findViewById(R.id.title_rightbtn1);
		rightTextView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				chooseCity();
			}
		});

		titleView = (TextView) view.findViewById(R.id.title_txt);

		sellerListView = (ListView) findViewById(R.id.seller_list);

		container = (FrameLayout) findViewById(R.id.seller_container);

		carCMPAdapter = new CarCMPAdapter();

		sellerListView.setAdapter(carCMPAdapter);

		sellerListView.setOnItemClickListener(this);

		pageIndex = 1;

		init();
	}

	private void chooseCity() {
		CityChooseDialog chooseDialog = new CityChooseDialog(activity);
	}

	/**
	 * 
	 */
	private void init() {
		switch (type) {
		case waysave:
			title = activity.getString(R.string.frag_head_txt_lujiu);
			break;
		case jzxc:
			title = activity.getString(R.string.chezhoubian_xiche);
			break;
		case upkeep:
			title = activity.getString(R.string.chezhoubian_baoyang);
			break;
		case weixiu:
			title = activity.getString(R.string.chezhoubian_weixiu);
			break;
		case travel:
			title = activity.getString(R.string.frag_head_txt_daijia);
			break;
		case pullcar:
			title = activity.getString(R.string.frag_head_txt_tuoche);
			break;
		default:
			title = "";
			break;
		}

		if (!TextUtils.isEmpty(title)) {
			getSellerList(pageIndex++);
			titleView.setText(title);
		}
	}

	/**
	 * @param pageIndex
	 *            int
	 */
	private void getSellerList(int pageIndex) {
		VolleyCenter.getVolley().addGetRequest(
				new GetSellerList(type, "115.909228", "28.65259", pageIndex),
				new VolleyListenerImpl<SellerListResponse>(
						new SellerListResponse()) {

					@Override
					public void deleveryResponse(SellerListResponse response) {
						sellers.addAll(response.getSellers());
						totalPages = response.getTotalPages();
						carCMPAdapter.notifyDataSetChanged();
					}
				});
	}

	/**
	 * @author Deve
	 * 
	 */
	private class CarCMPAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			if (sellers == null || sellers.size() == 0) {
				return 1;
			} else {
				if (pageIndex <= totalPages) {
					return sellers.size() + 1;
				}
			}
			return sellers.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (sellers == null || sellers.size() == 0) {
				return getTextView("该地区没有商家服务", parent);// 无数据的情况
			}
			if (pageIndex <= totalPages && position == getCount() - 1) {
				TextView textView = getTextView("点击加载更多", parent);// 当滑动到底部还有更多数据时
				textView.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						getSellerList(pageIndex++);
					}
				});
				return textView;
			}
			View currentView = convertView;
			Seller seller = sellers.get(position);
			if (currentView == null || currentView instanceof TextView) {
				currentView = activity.inflater.inflate(
						R.layout.seller_listitem, parent, false);

				currentView
						.setTag(new SellerItemHolder(
								(ImageView) currentView
										.findViewById(R.id.seller_listitem_iv),
								(TextView) currentView
										.findViewById(R.id.seller_listitem_shopname),
								(TextView) currentView
										.findViewById(R.id.seller_listitem_distance),
								(TextView) currentView
										.findViewById(R.id.seller_listitem_good),
								(TextView) currentView
										.findViewById(R.id.seller_listitem_price_last),
								(TextView) currentView
										.findViewById(R.id.seller_listitem_price_current),
								(TextView) currentView
										.findViewById(R.id.seller_listitem_hui)));
			}
			SellerItemHolder daijiaItemHolder = (SellerItemHolder) currentView
					.getTag();
			initHolderData(seller, daijiaItemHolder);
			return currentView;
		}
	}

	/**
	 * @param txt
	 * @return
	 */
	private TextView getTextView(String txt, ViewGroup viewGroup) {
		TextView textView = (TextView) activity.inflater.inflate(
				R.layout.listitem_txt, viewGroup, false);
		textView.setText(txt);
		textView.setClickable(true);
		return textView;
	}

	/**
	 * @param seller
	 *            Seller
	 * @param itemHolder
	 *            DaijiaItemHolder
	 */
	private void initHolderData(final Seller seller,
			final SellerItemHolder itemHolder) {
		itemHolder.cmpName.setText(seller.getShopName());
		itemHolder.distance.setText(StringUtils.parseDistance(seller
				.getDistance()));
		if (seller.getMinPrice().doubleValue() > 0) {
			itemHolder.curentPrice.setText(StringUtils.parseMoney(seller
					.getMinPrice()));
		}
		if (type == ServiceType.travel) {
			itemHolder.good.setVisibility(View.GONE);
			itemHolder.lastPrivice.setVisibility(View.GONE);
		} else {
			itemHolder.good.setVisibility(View.VISIBLE);
			itemHolder.good.setText(seller.getGoodNum() + "");
		}

		if (seller.getShopLogoBitmap() == null) {
			itemHolder.logo.setImageResource(R.drawable.wupeitu);
			VolleyCenter.getVolley().addImageRequest(seller.getShopLogo(),
					new Response.Listener<Bitmap>() {

						@Override
						public void onResponse(Bitmap response) {
							seller.setShopLogoBitmap(response);
							itemHolder.logo.setImageBitmap(response);
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							itemHolder.logo
									.setImageResource(R.drawable.wupeitu);
						}
					});
		} else {
			itemHolder.logo.setImageBitmap(seller.getShopLogoBitmap());
		}
	}

	@Override
	public void onBackPressed() {
		if (detailView != null && isDetailShow()) {
			container.removeView(detailView);
			detailView = null;
			isDetailShow = false;
			container.addView(sellerListView);
			titleView.setText(title);
		} else {
			super.onBackPressed();
			detailView = null;
		}
	}

	private boolean isDetailShow() {
		return isDetailShow;
	}

	private class SellerItemHolder {
		final ImageView logo;
		final TextView cmpName;
		final TextView distance;
		final TextView good;
		final TextView lastPrivice;
		final TextView curentPrice;
		final TextView youhui;

		/**
		 * @param logo
		 * @param cmpName
		 * @param distance
		 */
		public SellerItemHolder(ImageView logo, TextView cmpName,
				TextView distance, TextView good, TextView privice,
				TextView lowerPrice, TextView youhui) {
			this.logo = logo;
			this.cmpName = cmpName;
			this.distance = distance;
			this.good = good;
			this.lastPrivice = privice;
			this.curentPrice = lowerPrice;
			lastPrivice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
			this.youhui = youhui;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (isDetailShow) {
			return;
		}
		final ViewHolder holder;
		if (type == ServiceType.pullcar) {
			titleView.setText("拖车");
			if (detailView == null) {
				detailView = activity.inflater.inflate(R.layout.tuoche_info,
						container, false);
				detailView.setTag(new TuoCheViewHolder(activity, detailView));
			}
			holder = (ViewHolder) detailView.getTag();
		} else if (type == ServiceType.travel) {
			titleView.setText("代驾公司");
			if (detailView == null) {
				detailView = activity.inflater.inflate(R.layout.dajia_cmp_info,
						container, false);
				detailView.setTag(new TravelViewHolder(activity, detailView));
			}
			holder = (ViewHolder) detailView.getTag();

		} else if (type == ServiceType.waysave) {
			titleView.setText("路救");
			if (detailView == null) {
				detailView = activity.inflater.inflate(
						R.layout.way_save_layout, container, false);
				detailView.setTag(new LujiuViewHolder(detailView, activity));
			}
			holder = (ViewHolder) detailView.getTag();
		} else {
			titleView.setText("商家详情");
			if (detailView == null) {
				detailView = activity.inflater.inflate(R.layout.seller_stores,
						container, false);
				detailView
						.setTag(new SellerInfoViewHolder(activity, detailView));
			}
			holder = (ViewHolder) detailView.getTag();
		}
		final Seller seller = sellers.get(position);

		getSellInfo(seller, holder);
		isDetailShow = true;
		container.removeView(sellerListView);
		container.addView(detailView);
	}

	/**
	 * @param seller
	 *            Seller
	 * @param viewHolder
	 *            ViewHolder
	 */
	private void getSellInfo(final Seller seller, final ViewHolder viewHolder) {
		if (sellerInfos.get(seller) == null) {
			if (type == ServiceType.waysave) {
				VolleyCenter.getVolley().addGetRequest(
						new GetWaySaveInfo(seller.getSellerId()),
						new VolleyListenerImpl<GetWaySaveResponse>(
								new GetWaySaveResponse()) {

							@Override
							public void deleveryResponse(
									GetWaySaveResponse response) {
								SellerInfo sellerInfo = response
										.getSellerInfo();
								sellerInfos.put(seller, sellerInfo);
								viewHolder.setData(seller, sellerInfo);
							}
						});
			} else if (type == ServiceType.travel
					|| type == ServiceType.pullcar) {
				VolleyCenter.getVolley().addGetRequest(
						new GetSellersTWO(type, seller.getSellerId()),
						new VolleyListenerImpl<SellerTWOResponse>(
								new SellerTWOResponse()) {

							@Override
							public void deleveryResponse(
									SellerTWOResponse response) {
								SellerInfo sellerInfo = response
										.getSellerInfo();
								sellerInfos.put(seller, sellerInfo);
								viewHolder.setData(seller, sellerInfo);
							}
						});
			} else {
				VolleyCenter.getVolley().addGetRequest(
						new GetSellerInfo(type, seller.getSellerId()),
						new VolleyListenerImpl<SellerInfoResponse>(
								new SellerInfoResponse()) {

							@Override
							public void deleveryResponse(
									SellerInfoResponse response) {
								SellerInfo sellerInfo = response
										.getSellerInfo();
								sellerInfos.put(seller, sellerInfo);
								viewHolder.setData(seller, sellerInfo);
							}
						});
			}
		} else {
			viewHolder.setData(seller, sellerInfos.get(seller));
		}
	}
}
